<?php
/**
 * Created by PhpStorm.
 * User: meiyun1
 * Date: 2017/2/24
 * Time: 下午1:30
 */

namespace App\Http\Controllers\App\RedpackRain;

use App\Exceptions\ExceptionCode;
use App\Http\Controllers\App\AppInterface;
use App\Http\Controllers\App\Controller;
use App\Models\Participant\Participant;

class IndexController extends Controller implements AppInterface
{
    public function participant()
    {
        $from = $this->request->query->get('from', Participant::SOURCE_APP);
        if (in_array($from, ['singlemessage'])) {
            $from = Participant::SOURCE_WECHAT;
        }
        if (in_array($from, [Participant::SOURCE_WECHAT, Participant::SOURCE_APP])) {
            $from = Participant::SOURCE_PC;
        }
        $openID = $this->request->query->get('openid');
        if (empty($openID)) {
            $openID = $this->request->cookie('openid');
        }
        $participant = $this->createParticipant($openID, $from);
        if (!empty($participant)) {
            return $this->respondJson(['code' => 0, 'participant' => $participant->toArray()]);
        }
        return $this->respondJson(['code' => ExceptionCode::GENERAL, 'message' => '参数错误']);
    }

    public function index($token)
    {
        $from = $this->request->query->get('from', Participant::SOURCE_APP);
        if (in_array($from, ['singlemessage'])) {
            $from = Participant::SOURCE_WECHAT;
        }
        if (in_array($from, [Participant::SOURCE_WECHAT, Participant::SOURCE_APP])) {
            $from = Participant::SOURCE_PC;
        }
        $openID = $this->request->query->get('openid');
        if(empty($openID)){
            $openID = $this->request->query->get('uid');
        }
        if (empty($token)) {
            abort(404);
        }
        try {
            $token = json_decode(base64_decode($token), true);
            if (empty($token)) {
                abort(404);
            }
            $activity_id = $token['activity_id'];
            if (empty($activity_id)) {
                abort(404);
            }

            $activity = $this->getActivityDetail($activity_id, $this->activityService);
            $this->updateActivityViews($activity_id, $this->activityService);
            $location = '/' . $activity['model']['rule'] . '/activity/detail?openid='.$openID;

            $participant = $this->createParticipant($openID, $from);
            if (empty($participant)) {
                return $this->respondJson([
                    'code' => ExceptionCode::GENERAL,
                    'message' => '用户信息丢失！'
                ]);
            }
            if ($from == Participant::SOURCE_WECHAT) {
                if (empty($participant)) {
                    $session = $this->request->session();
                    $session->put('target_url', $this->request->fullUrl());
                    $oauth = $this->wechatService->getWechatApp()->oauth;
                    return $oauth->redirect();
                }
            } else {
            }

            return response()->redirectTo($location)->cookie('token', base64_encode(json_encode($token)))
                ->cookie('hasView:' . $activity_id, true, 36000000)
                ->cookie('from', $from)
                ->cookie('openid', $participant->id);
        } catch (\Exception $exception) {
            abort(404, $exception->getMessage());
        }
    }

    public function activity()
    {
        $activity_id = $this->request->query->get('id');
        $openID = $this->request->query('openid');

        $from = Participant::SOURCE_APP;
        if (empty($activity_id)) {
            $token = $this->request->cookie('token');
            $from = $this->request->cookie('from');
            $openID = $this->request->cookie('openid');
            if (empty($token)) {
                abort(404);
            }
            $token = json_decode(base64_decode($token), true);
            $activity_id = $token['activity_id'];
            if (empty($activity_id)) {
                abort(404);
            }
        }
        $participant = $this->getParticipantByID($openID);
        $activity = $this->getActivityDetail($activity_id);

        $prizes = collect($activity['prizes'])->pluck('prize_id')->toArray();
        $sponsors = $this->sponsorService->getSponsorByPrizeIds($prizes);
        foreach ($sponsors as &$row) {
            $row['logo'] = $this->storageService->tomedia($row['logo']);
        }
        unset($row);
        if ($from == Participant::SOURCE_WECHAT) {
            if (empty($participant)) {
                session('target_url', $this->request->getHttpHost() . '/' . $activity['model']['rule'] . '/activity/index/' . base64_encode(json_encode(['activity_id' => $activity_id])) . '?from=' . Participant::SOURCE_WECHAT);
                $oauth = $this->wechatService->getWechatApp()->oauth;
                return $oauth->redirect();
            }
        }
        //var_dump($openid);
        //$prizelist = $this->getActivityPrizes($activity_id);
        //$res = $this->getLuckPrizeByActivity($activity_id,$openid);
        //dd($res);
        // TODO: Implement activity() method.
        $wechatApp = $this->wechatService->getWechatApp();
        $share_url = $this->request->getSchemeAndHttpHost() . '/redpack_rain/activity/index/' . base64_encode(json_encode(['activity_id' => $activity_id]));
        return view('app.' . $activity['model']['rule'] . '.' . $activity['template']['template'] . '.index', [
            'activity' => $activity,
            'activity_template' => $activity['model']['rule'] . '/' . $activity['template']['template'],
            'from' => $from,
            'openid' => $participant->id,
            'sponsors' => $sponsors,
            'wxjs' => $wechatApp->js,
            'share_url' => $share_url
        ]);
    }

    public function luckDraw()
    {
        $activity_id = $this->request->request->get('id');
        $openid = $this->request->request->get('openid');
        $redpack = $this->request->request->get('redpack');

        $activity = $this->getActivityDetail($activity_id);
        if (empty($activity)) {
            return $this->respondJson([
                'code' => ExceptionCode::GENERAL,
                'message' => '活动不存在！'
            ]);
        }
        if (strtotime($activity['startTime']) > time()) {
            return $this->respondJson([
                'code' => ExceptionCode::GENERAL,
                'message' => '活动还未开始！'
            ]);
        }
        if (strtotime($activity['endTime']) < time()) {
            return $this->respondJson([
                'code' => ExceptionCode::GENERAL,
                'message' => '活动已经结束'
            ]);
        }

        if (empty($openid)) {
            return $this->respondJson([
                'code' => ExceptionCode::GENERAL,
                'message' => '请登陆后参与活动！'
            ]);
        }
        $rule = json_decode($activity['rule'], true);
        if (empty($redpack) || $redpack < $rule['basic']['min_num']) {
            return $this->respondJson([
                'code' => ExceptionCode::GENERAL,
                'message' => '不满足参与活动条件！'
            ]);
        }
        $luckPrize = $this->getLuckPrizeByActivity($activity_id, $openid);
        return $this->respondJson($luckPrize);
    }

    public function receive()
    {
        $activity_id = $this->request->request->get('activity_id');
        $prize_id = $this->request->request->get('prize_id');
        $id = $this->request->request->get('openid');
        $participant = $this->getParticipantByID($id);
        $name = $this->request->request->get('name');
        $mobile = $this->request->request->get('mobile');
        $address = $this->request->request->get('address', '');

        if (empty($activity_id) || empty($prize_id) || empty($id)) {
            return $this->respondJson([
                'code' => ExceptionCode::GENERAL,
                'message' => '参数错误'
            ]);
        }
        $userInfo = [
            'participantid' => $participant->id,
            'openid' => $participant->openid,
            'name' => $name,
            'mobile' => $mobile,
            'address' => $address,
            'alipay' => $mobile
        ];
        return $this->respondJson($this->receivePrize($activity_id, $prize_id, $userInfo));
    }


    public function preview($model, $template)
    {
        // TODO: Implement preview() method.
        $activity_template = $model . '/' . $template;
        $time = $this->request->request->get('time', 30);
        $background = $this->request->request->get('background', "/app/{$activity_template}/img/bg.jpg");
        return view("app.{$model}.{$template}.preview", [
            'activity_template' => $activity_template,
            'time' => $time,
            'background' => $this->storageService->tomedia($background)
        ]);
    }
}
